package com.ge.myoned.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ge.myoned.service.TestLockService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author geqingxiang
 * @PackageName myProject
 * @Package com.example.myproject.service
 * @Date 2023/4/18 17:00
 * @Version 1.0
 */
@Service
@Slf4j
public class TestLockServiceImpl implements TestLockService {
    @Autowired
    private RedissonClient redissonClient;
    private final static String LOCK="i_am_lock";


    @Override
    public void testLockOne() {
        long start = System.currentTimeMillis();
        //获取锁
        RLock lock = redissonClient.getLock(LOCK);
        //加锁
        lock.lock();
        long time = System.currentTimeMillis()-start;
        //这里看看多久之后才能够获取锁，能够执行下面的语句
        log.info("线程：{}，过了{}s获取锁", Thread.currentThread().getName(), time/1000);
        int c = RandomUtil.randomInt(1, 10000);
        try {
            Thread.sleep(c);
            log.info("线程：{}，休眠时间:{}毫秒", Thread.currentThread().getName(),c);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //释放锁
        lock.unlock();
    }
}
